<template>
  <div class="data-service-management">
    <!-- 顶部操作栏 -->
    <div class="header">
      <el-input
        v-model="search"
        placeholder="搜索API..."
        class="search-input"
        size="small"
        clearable
      />
      <el-button type="primary" size="small" @click="showApiDialog = true">新建API</el-button>
      <el-button size="small" @click="showModelDialog = true">导入模型</el-button>
    </div>

    <el-row :gutter="20" class="main-content">
      <!-- 左侧API管理 -->
      <el-col :span="14">
        <el-card shadow="never" class="api-card">
          <div slot="header" class="api-card-header">
            <span>数据接口管理</span>
          </div>
          <el-table
            :data="filteredApis"
            style="width: 100%"
            size="small"
            :header-cell-style="{background:'#f5f7fa',color:'#333'}"
          >
            <el-table-column prop="name" label="API名称" width="180"/>
            <el-table-column prop="dataType" label="数据类型" width="120"/>
            <el-table-column prop="method" label="请求方式" width="80"/>
            <el-table-column prop="createdAt" label="创建时间" width="120"/>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '运行中' ? 'success' : 'info'" size="mini">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    更多<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="editApi(scope.row)">编辑</el-dropdown-item>
                    <el-dropdown-item @click.native="deleteApi(scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 分析模型接口区 -->
        <el-card shadow="never" class="model-card" style="margin-top: 20px;">
          <div slot="header" class="api-card-header">
            <span>分析模型接口</span>
          </div>
          <el-table
            :data="models"
            style="width: 100%"
            size="small"
            :header-cell-style="{background:'#f5f7fa',color:'#333'}"
          >
            <el-table-column prop="name" label="模型名称" width="180"/>
            <el-table-column prop="language" label="语言" width="80"/>
            <el-table-column prop="restUrl" label="RESTful地址"/>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '已启用' ? 'success' : 'info'" size="mini">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧性能监控与服务市场 -->
      <el-col :span="10">
        <el-card shadow="never" class="monitor-card">
          <div slot="header" class="api-card-header">
            <span>性能监控</span>
          </div>
          <div class="monitor-content">
            <div class="monitor-item">
              <div class="monitor-label">QPS监控</div>
              <div class="monitor-value">{{ qps }}</div>
            </div>
            <div class="monitor-item">
              <div class="monitor-label">接口延迟</div>
              <div class="monitor-value">{{ latency }}ms</div>
            </div>
            <div class="monitor-item">
              <div class="monitor-label">平均延迟</div>
              <div class="monitor-value">{{ avgLatency }}ms</div>
            </div>
          </div>
        </el-card>

        <!-- 服务市场 -->
        <el-card shadow="never" class="market-card" style="margin-top: 20px;">
          <div slot="header" class="api-card-header">
            <span>服务市场</span>
            <el-button type="primary" size="mini" style="float:right" @click="showPublishDialog = true">发布服务</el-button>
          </div>
          <el-row :gutter="10">
            <el-col :span="12" v-for="service in services" :key="service.id" style="margin-bottom: 10px;">
              <el-card :body-style="{padding:'10px'}" class="service-item">
                <div class="service-title">
                  <i :class="service.icon" style="margin-right:6px"></i>{{ service.name }}
                  <el-tag v-if="service.subscribed" type="success" size="mini" style="float:right">已订阅</el-tag>
                </div>
                <div class="service-desc">{{ service.desc }}</div>
                <el-button
                  v-if="!service.subscribed"
                  type="primary"
                  size="mini"
                  @click="subscribeService(service)"
                  style="margin-top:6px"
                >订阅</el-button>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 低代码报表拖拽区 -->
    <el-card shadow="never" class="lowcode-card" style="margin-top: 20px;">
      <div slot="header" class="api-card-header">
        <span>数据服务超市 - 低代码报表</span>
      </div>
      <div class="lowcode-content">
        <div class="components-list">
          <div
            class="draggable-component"
            v-for="comp in reportComponents"
            :key="comp.type"
            draggable="true"
            @dragstart="onDragStart(comp)"
          >
            <i :class="comp.icon"></i> {{ comp.name }}
          </div>
        </div>
        <div
          class="canvas"
          @dragover.prevent
          @drop="onDrop"
        >
          <div v-if="canvasComponents.length === 0" class="canvas-placeholder">
            拖拽组件到此处
          </div>
          <div
            v-for="(comp, idx) in canvasComponents"
            :key="idx"
            class="canvas-component"
          >
            <div class="canvas-component-header">
              <span>{{ comp.name }}</span>
              <el-button type="text" size="mini" @click="removeCanvasComponent(idx)">移除</el-button>
            </div>
            <div class="canvas-component-body">
              <el-form :model="comp.config" label-width="80px" size="mini">
                <el-form-item label="数据表">
                  <el-select v-model="comp.config.table" placeholder="选择数据表">
                    <el-option label="设备能耗数据表" value="energy"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间维度">
                  <el-radio-group v-model="comp.config.timeDim">
                    <el-radio label="日">日</el-radio>
                    <el-radio label="周">周</el-radio>
                    <el-radio label="月">月</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="图表类型">
                  <el-radio-group v-model="comp.config.chartType">
                    <el-radio label="line">折线图</el-radio>
                    <el-radio label="bar">柱状图</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
              <div class="chart-preview">
                <chart-preview
                  :type="comp.config.chartType"
                  :time-dim="comp.config.timeDim"
                  :table="comp.config.table"
                  :mock-data="energyData"
                />
              </div>
              <el-button
                type="primary"
                size="mini"
                @click="saveReport(comp)"
                style="margin-top:8px"
              >保存并生成访问链接</el-button>
              <div v-if="comp.link" class="report-link">
                访问链接：<a :href="comp.link" target="_blank">{{ comp.link }}</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 新建API弹窗 -->
    <el-dialog title="新建API" :visible.sync="showApiDialog" width="500px">
      <el-form :model="apiForm" label-width="100px">
        <el-form-item label="API名称">
          <el-input v-model="apiForm.name"/>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="apiForm.dataType" placeholder="请选择">
            <el-option label="原始设备数据" value="原始数据"/>
            <el-option label="清洗后数据" value="清洗数据"/>
          </el-select>
        </el-form-item>
        <el-form-item label="请求方式">
          <el-radio-group v-model="apiForm.method">
            <el-radio label="GET">GET</el-radio>
            <el-radio label="POST">POST</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请求参数">
          <el-checkbox-group v-model="apiForm.params">
            <el-checkbox label="设备ID"/>
            <el-checkbox label="时间范围"/>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="响应格式">
          <el-tag type="info">JSON</el-tag>
        </el-form-item>
        <el-form-item label="QPS测试">
          <el-input v-model="apiForm.qps" placeholder="如50" style="width:100px" size="mini"/>
          <span style="margin-left:8px">接口延迟≤300ms</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showApiDialog = false">取 消</el-button>
        <el-button type="primary" @click="createApi">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导入模型弹窗 -->
    <el-dialog title="导入Python模型" :visible.sync="showModelDialog" width="500px">
      <el-form :model="modelForm" label-width="100px">
        <el-form-item label="模型名称">
          <el-input v-model="modelForm.name"/>
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload
            action=""
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleModelFile"
          >
            <el-button size="small" type="primary">选择Python文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showModelDialog = false">取 消</el-button>
        <el-button type="primary" @click="importModel">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 发布服务弹窗 -->
    <el-dialog title="发布智能服务" :visible.sync="showPublishDialog" width="400px">
      <el-form :model="publishForm" label-width="100px">
        <el-form-item label="服务名称">
          <el-input v-model="publishForm.name"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="publishForm.desc"/>
        </el-form-item>
        <el-form-item label="图标">
          <el-select v-model="publishForm.icon">
            <el-option label="折线图" value="el-icon-data-analysis"/>
            <el-option label="饼图" value="el-icon-pie-chart"/>
            <el-option label="表格" value="el-icon-s-grid"/>
            <el-option label="趋势" value="el-icon-trend-charts"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPublishDialog = false">取 消</el-button>
        <el-button type="primary" @click="publishService">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入element-ui和echarts
import { Message } from 'element-ui'

// 简单的图表预览组件
const ChartPreview = {
  props: ['type', 'timeDim', 'table', 'mockData'],
  mounted() {
    this.renderChart()
  },
  watch: {
    type() { this.renderChart() },
    timeDim() { this.renderChart() },
    table() { this.renderChart() }
  },
  methods: {
    renderChart() {
      if (!this.$refs.chart) return
      const echarts = require('echarts')
      const chart = echarts.init(this.$refs.chart)
      let option = {}
      let data = this.mockData[this.timeDim] || []
      if (this.type === 'line') {
        option = {
          xAxis: { type: 'category', data: data.map(d => d.label) },
          yAxis: { type: 'value' },
          series: [{ data: data.map(d => d.value), type: 'line', smooth: true }]
        }
      } else {
        option = {
          xAxis: { type: 'category', data: data.map(d => d.label) },
          yAxis: { type: 'value' },
          series: [{ data: data.map(d => d.value), type: 'bar' }]
        }
      }
      chart.setOption(option)
    }
  },
  render(h) {
    return h('div', {
      ref: 'chart',
      style: { width: '100%', height: '180px' }
    })
  }
}

export default {
  name: 'DataServiceManagement',
  components: {
    ChartPreview
  },
  data() {
    return {
      search: '',
      showApiDialog: false,
      showModelDialog: false,
      showPublishDialog: false,
      apiForm: {
        name: '',
        dataType: '',
        method: 'GET',
        params: [],
        qps: 50
      },
      modelForm: {
        name: '',
        file: null
      },
      publishForm: {
        name: '',
        desc: '',
        icon: ''
      },
      apis: [],
      models: [],
      services: [],
      reportComponents: [
        { type: 'line', name: '折线图组件', icon: 'el-icon-data-analysis' },
        { type: 'bar', name: '柱状图组件', icon: 'el-icon-s-data' }
      ],
      canvasComponents: [],
      dragComponent: null,
      // mock能耗数据
      energyData: {
        日: [
          { label: '2024-01-18', value: 120 },
          { label: '2024-01-19', value: 132 },
          { label: '2024-01-20', value: 101 },
          { label: '2024-01-21', value: 134 },
          { label: '2024-01-22', value: 90 }
        ],
        周: [
          { label: '第1周', value: 800 },
          { label: '第2周', value: 950 },
          { label: '第3周', value: 700 },
          { label: '第4周', value: 1100 }
        ],
        月: [
          { label: '1月', value: 3200 },
          { label: '2月', value: 2800 },
          { label: '3月', value: 3500 }
        ]
      },
      qps: 50,
      latency: 280,
      avgLatency: 305
    }
  },
  computed: {
    filteredApis() {
      if (!this.search) return this.apis
      return this.apis.filter(api => api.name.includes(this.search))
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 本地存储
    saveData() {
      localStorage.setItem('ds_apis', JSON.stringify(this.apis))
      localStorage.setItem('ds_models', JSON.stringify(this.models))
      localStorage.setItem('ds_services', JSON.stringify(this.services))
      localStorage.setItem('ds_reports', JSON.stringify(this.canvasComponents))
    },
    loadData() {
      // mock初始化
      const apis = localStorage.getItem('ds_apis')
      const models = localStorage.getItem('ds_models')
      const services = localStorage.getItem('ds_services')
      const reports = localStorage.getItem('ds_reports')
      this.apis = apis
        ? JSON.parse(apis)
        : [
            {
              name: '设备能耗数据接口',
              dataType: '原始数据',
              method: 'GET',
              createdAt: '2024-01-20',
              status: '运行中'
            },
            {
              name: '清洗后数据接口',
              dataType: '清洗数据',
              method: 'POST',
              createdAt: '2024-01-19',
              status: '已停用'
            },
            {
              name: '实时监控数据接口',
              dataType: '原始数据',
              method: 'GET',
              createdAt: '2024-01-18',
              status: '运行中'
            }
          ]
      this.models = models
        ? JSON.parse(models)
        : [
            {
              name: '能耗预测模型',
              language: 'Python',
              restUrl: '/api/v1/models/能耗预测模型',
              status: '已启用'
            }
          ]
      this.services = services
        ? JSON.parse(services)
        : [
            {
              id: 1,
              name: '故障预警服务',
              desc: '设备异常自动预警，支持API集成',
              icon: 'el-icon-warning-outline',
              subscribed: false
            },
            {
              id: 2,
              name: '能耗分析服务',
              desc: '多维度能耗分析，支持报表输出',
              icon: 'el-icon-data-analysis',
              subscribed: false
            }
          ]
      this.canvasComponents = reports ? JSON.parse(reports) : []
    },
    // API管理
    createApi() {
      if (!this.apiForm.name || !this.apiForm.dataType) {
        Message.warning('请填写完整信息')
        return
      }
      this.apis.push({
        name: this.apiForm.name,
        dataType: this.apiForm.dataType,
        method: this.apiForm.method,
        createdAt: new Date().toISOString().slice(0, 10),
        status: '运行中'
      })
      this.saveData()
      this.showApiDialog = false
      this.apiForm = {
        name: '',
        dataType: '',
        method: 'GET',
        params: [],
        qps: 50
      }
      Message.success('API创建成功')
    },
    editApi(api) {
      Message.info('编辑功能可扩展')
    },
    deleteApi(api) {
      this.$confirm('确定删除该API吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.apis = this.apis.filter(a => a !== api)
        this.saveData()
        Message.success('已删除')
      })
    },
    // 模型导入
    handleModelFile(file) {
      this.modelForm.file = file
    },
    importModel() {
      if (!this.modelForm.name) {
        Message.warning('请填写模型名称')
        return
      }
      this.models.push({
        name: this.modelForm.name,
        language: 'Python',
        restUrl: `/api/v1/models/${this.modelForm.name}`,
        status: '已启用'
      })
      this.saveData()
      this.showModelDialog = false
      this.modelForm = { name: '', file: null }
      Message.success('模型导入成功')
    },
    // 服务市场
    subscribeService(service) {
      service.subscribed = true
      this.saveData()
      Message.success('订阅成功')
    },
    publishService() {
      if (!this.publishForm.name) {
        Message.warning('请填写服务名称')
        return
      }
      this.services.push({
        id: Date.now(),
        name: this.publishForm.name,
        desc: this.publishForm.desc,
        icon: this.publishForm.icon || 'el-icon-data-analysis',
        subscribed: false
      })
      this.saveData()
      this.showPublishDialog = false
      this.publishForm = { name: '', desc: '', icon: '' }
      Message.success('服务已发布')
    },
    // 低代码报表拖拽
    onDragStart(comp) {
      this.dragComponent = comp
    },
    onDrop() {
      if (this.dragComponent) {
        this.canvasComponents.push({
          ...this.dragComponent,
          config: {
            table: 'energy',
            timeDim: '日',
            chartType: this.dragComponent.type
          },
          link: ''
        })
        this.saveData()
        this.dragComponent = null
      }
    },
    removeCanvasComponent(idx) {
      this.canvasComponents.splice(idx, 1)
      this.saveData()
    },
    saveReport(comp) {
      // 生成一个本地访问链接（模拟）
      comp.link = `${window.location.origin}/report/${Date.now()}`
      this.saveData()
      Message.success('报表已保存，访问链接已生成')
    }
  }
}
</script>

<style scoped>
.data-service-management {
  padding: 20px;
  background: #f5f7fa;
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.search-input {
  width: 220px;
  margin-right: 12px;
}
.api-card, .model-card, .monitor-card, .market-card, .lowcode-card {
  margin-bottom: 0;
}
.api-card-header {
  font-weight: bold;
  font-size: 15px;
}
.monitor-content {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}
.monitor-item {
  flex: 1;
  text-align: center;
}
.monitor-label {
  color: #888;
  font-size: 13px;
}
.monitor-value {
  font-size: 20px;
  font-weight: bold;
  margin-top: 4px;
}
.service-item {
  min-height: 80px;
}
.service-title {
  font-weight: bold;
  font-size: 14px;
}
.service-desc {
  color: #888;
  font-size: 12px;
  margin-top: 2px;
}
.lowcode-content {
  display: flex;
  align-items: flex-start;
}
.components-list {
  width: 120px;
  margin-right: 20px;
}
.draggable-component {
  background: #fff;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  text-align: center;
  cursor: grab;
  transition: box-shadow .2s;
}
.draggable-component:hover {
  box-shadow: 0 2px 8px #eee;
}
.canvas {
  flex: 1;
  min-height: 220px;
  background: #fafbfc;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  display: flex;
  flex-direction: column;
}
.canvas-placeholder {
  color: #bbb;
  text-align: center;
  margin-top: 60px;
}
.canvas-component {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 16px;
  padding: 12px;
}
.canvas-component-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  margin-bottom: 8px;
}
.chart-preview {
  width: 100%;
  height: 180px;
  margin-top: 8px;
  background: #f8f8fa;
  border-radius: 4px;
}
.report-link {
  margin-top: 6px;
  font-size: 13px;
  color: #409EFF;
  word-break: break-all;
}
</style>
